<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-14
 * Time: 下午4:53
 */

namespace api\modules\big_data\controllers;

use common\components\big_data\BaiRong;
use common\components\big_data\bairong\Core;
use common\components\big_data\Config;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\BaiRongValidateForCreditOrder;
use common\models\BaiRongValidateLog;
use common\models\CreditOrder;
use common\models\FicoEarlyWarning;
use wodrow\yii\rest\ApiException;
use yii\base\ErrorException;
use yii\httpclient\Client;
use yii\httpclient\Request;

class ValidateController extends \wodrow\yii\rest\Controller
{
    /**
     * 实名反欺诈 [已废弃]
     * @desc get/post /big_data/validate/real-name-anti-fraud
     * @param string $ID_card 身份证
     * @param string $mobile 手机号
     * @param string $name 客户姓名
     * @param string $company 公司标号
     * @param string $other_data 其他数据[serialize]
     */
    public function actionRealNameAntiFraud($ID_card, $mobile, $name, $company='yishang', $other_data = null)
    {
        if ($other_data)$other_data = unserialize($other_data);
        switch ($company){
            case 'baoze':
                $br = \Yii::$app->bairong1;
                break;
            default:
                $br = \Yii::$app->bairong0;
                break;
        }
        $data = $br->check($name, $ID_card, $mobile);
        return $data;
    }

    /**
     * 嵌入式报告 [百融] [已废弃]
     * @desc get/post
     * @param string $swift_number
     * @param string $company 公司标号
     */
    public function actionReport($swift_number, $br_conf='bairong0')
    {
        $br = \Yii::$app->$br_conf;
        $str7 = substr($swift_number, 0, 7);
        if ($str7 == '3002137')$br = \Yii::$app->bairong0;
//        if ($str7 == '3002208')$br = \Yii::$app->bairong1;
        $login_data = $br->getWebLoginData();
        $token = $login_data['tokenid'];
        $url = "https://apiservice.100credit.com/v/#/userReport/{$swift_number}/{$token}";
        /*if ($br_conf == 'bairong1'){
            $swift_number = substr($swift_number, 8);
            $url = "https://apiservice.100credit.com/zuul/api/examin-service/examine/history/singlePdfExport?swift_number={$swift_number}&type=1&sessionId={$token}";
        }*/
//        $url = "https://infocheck.100credit.com/#/userReport/{$swift_number}/{$token}";
//        var_dump($url);exit;
        header("Location: ".$url);
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        exit;
    }

    /**
     * 征信百融查询认证 [百融]
     * @param string $credit_order_id 征信订单号
     */
    public function actionBairongValidateForCreditOrder($credit_order_id)
    {
        $credit_order = CreditOrder::findOne($credit_order_id);
        if (!$credit_order){
            throw new ErrorException("没有找到征信");
        }
        $bairong_conf = $credit_order->guaranteeCompanyDotSite->link_bairong_component_conf;
        /**
         * @var BaiRong $br
         */
        $br = \Yii::$app->$bairong_conf;
        $data = $br->check($credit_order->custname, $credit_order->idno, $credit_order->mobile);
        foreach ($data['validate_log'] as $k => $v){
            $bind = BaiRongValidateForCreditOrder::findOne(['credit_order_id' => $credit_order->id, 'bai_rong_validate_log_id' => $v['id']]);
            if (!$bind){
                $bind = new BaiRongValidateForCreditOrder();
                $bind->credit_order_id = $credit_order->id;
                $bind->bai_rong_validate_log_id = $v['id'];
                $bind->created_at = time();
                if (!$bind->save()){
                    throw new ErrorException("保存数据失败".var_export($bind->errors, true));
                }
            }
        }
        $data['credit_order'] = $credit_order->toArray();
        $data['bairong_result'] = $credit_order->getBairongResult();
        return $data;
    }

    /**
     * 获取优化后的响应信息 [百融]
     * @desc get/post
     * @param $credit_order_id
     * @throws ErrorException
     */
    public function actionOptimizeBairongApiResult($credit_order_id)
    {
        $credit_order = CreditOrder::findOne($credit_order_id);
        if (!$credit_order){
            throw new ErrorException("没有找到征信");
        }
        $br_data = $credit_order->getBairongResult();
        $r ['optimize_show'] = $br_data['optimize_show'];
        return $r;
    }

    /**
     * 征信嵌入式报告 [百融]
     * @desc get/post
     * @param string $swift_number
     */
    public function actionBairongReport($credit_order_id)
    {
        $credit_order = CreditOrder::findOne($credit_order_id);
        if (!$credit_order){
            throw new ErrorException("没有找到征信");
        }
        $br_data = $credit_order->getBairongResult();
        return $br_data['url'];
    }

    /**
     * 百融直接选择配置获取认证信息 [百融]
     * @param string $br_conf
     * @param string $name
     * @param string $idcard
     * @param string $mobile
     * @param string $other_data
     * @param int $import_type
     * @param int $re_check 重新查询
     * @return array
     * @throws ErrorException
     */
    public function actionBairongValidate($br_conf, $name, $idcard, $mobile, $other_data = '', $import_type = BaiRongValidateLog::IMPORT_TYPE_DEFAULT, $re_check = 0)
    {
        $name = trim($name);
        $idcard = trim($idcard);
        $mobile = trim($mobile);
        /**
         * @var BaiRong $br
         */
        $br = \Yii::$app->$br_conf;
        $r = $br->check($name, $idcard, $mobile, 0, $other_data, $import_type, $re_check);
//        return $data;
        $url = [];
        $swift_numbers = [];
        /**
         * @var BaiRongValidateLog[] $logs
         */
        $logs = $r['validate_log'];
        foreach ($logs as $k => $v) {
            $v->showOtherData();
            $swift_number = $v->resp_swift_number;
            $strategy_type = $v->strategy_type;
            $swift_numbers[$strategy_type] = $swift_number;
            $login_data = $br->getWebLoginData();
            $token = $login_data['tokenid'];
            $url[$strategy_type] = $br->selectStrategy($br->need_strategys[$strategy_type])['report_url_pre']."{$swift_number}/{$token}";
        }
        $r['swift_numbers'] = $swift_numbers;
        $r['url'] = $url;
        $str = '';
        foreach ($logs as $k => $v) {
            if ($v->strategy_type == BaiRongValidateLog::STRATEGY_TYPE_DETAIL_LIST){
                $str .= $br->formatDetailList($v->resp_data_for_api_send, 1);
            }
            if ($v->strategy_type == BaiRongValidateLog::STRATEGY_TYPE_PERSON_RECOGNITION){
                if ($v->is_old_from_console){
                    $str .= $br->formatPersionRecognitionOld($v->resp_data_for_api_send, 1);
                }else{
                    $str .= $br->formatPersionRecognition($v->resp_data_for_api_send, 1);
                }
            }
        }
        $r['optimize_show'] = $br->optimizeShowStr($str);
        return $r;
    }

    /**
     * fico 大数据预警
     * @param string $mobile
     * @param string $idcard
     * @param int $re_check 重新查询
     * @throws ApiException
     * @throws \yii\base\Exception
     */
    public function actionFicoScore($mobile, $idcard, $other_data = '', $import_type = FicoEarlyWarning::IMPORT_TYPE_DEFAULT, $re_check = 0)
    {
        $fico_ew = FicoEarlyWarning::findOne(['mobile' => $mobile, 'idcard' => $idcard]);
        if (!$fico_ew || $re_check){
            if (!$fico_ew){
                $fico_ew = new FicoEarlyWarning();
                $fico_ew->mobile = $mobile;
                $fico_ew->idcard = $idcard;
            }
            $fico_ew->created_at = time();
            $url = Config::$fico['get_score_url'];
            $clientId = Config::$fico['clientId'];
            $password = Config::$fico['password'];
            $pboc = Config::$fico['pboc'];
            $mobHeader = Config::$fico['mobHeader'];
            $serviceCode = Config::$fico['serviceCode'];
            $mobile = hash("sha256", $mobile);
            $idCard = hash("sha256", $idcard);
            $xml = <<<xml
<?xml version="1.0" encoding="UTF-8"?>
<Request clientID="{$clientId}" password="{$password}" pboc="{$pboc}" mobHeader="{$mobHeader}" serviceCode="{$serviceCode}" mobile="{$mobile}" idCard="{$idCard}" />
xml;
            $req = new \GuzzleHttp\Client(['verify' => false]);
            $resp = $req->post($url, [
                'body' => $xml
            ]);
            $resp_xml = $resp->getBody()->getContents();
            $data = Tools::xmlToArray($resp_xml);
            $_d = $data['@attributes'];
            $fico_ew->ret_code = $_d['retCode'];
            $fico_ew->score_id = $_d['scoreID'];
            $fico_ew->resp_data = $resp_xml;
            if (isset($_d['errMsg'])){$fico_ew->err_msg = $_d['errMsg'];}else{$fico_ew->err_msg = '';}
            if (isset($_d['reason'])){$fico_ew->reason = $_d['reason'];}else{$fico_ew->reason = '';}
            if (isset($_d['riskLevel'])){$fico_ew->risk_level = $_d['riskLevel'];}else{$fico_ew->risk_level = '';}
            $fico_ew->other_data = $other_data;
            $fico_ew->import_type = $import_type;
            if (!$fico_ew->save()){
                throw new ApiException(88241421, "fico大数据预警保存失败:".Model::getModelError($fico_ew));
            }
        }
        $reason_map_arr = [];
        if ($fico_ew->reason){
            foreach (Tools::str2arr($fico_ew->reason) as $k => $v){
                $reason_map_arr[] = FicoEarlyWarning::$reasonMap[$v];
            }
        }
        $reason_detail = Tools::arr2str($reason_map_arr);
        $r = [
            'fico_early_warning' => $fico_ew->toArray(),
            'reason_detail' => $reason_detail,
        ];
        return $r;
    }

    /**
     * fico loan 请求放款借款
     */
    public function actionFicoLoan()
    {
        $url = "http://partnertest.mypicc.com.cn/ecooperation/Uinsured/loan.do";
        $xml = <<<xml
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<LoanInfo>
    <ProposalNo></ProposalNo>
    <ApplyLoanTimes></ApplyLoanTimes>
    <Applicant></Applicant>
    <BankCode></BankCode>
</LoanInfo>
xml;
        $req = new \GuzzleHttp\Client(['verify' => false]);
        $resp = $req->post($url, [
            'body' => $xml
        ]);
        var_dump($resp->getBody()->getContents());
        exit;
    }

    /**
     * fico pretrial 这是银行预审申请接口
     */
    public function actionFicoPretrial()
    {
        $url = "http://partnertest.mypicc.com.cn/ecooperation/Uinsured/pretrial.do";
        $xml = <<<xml
<?xml version='1.0' encoding='UTF-8'?>
<PrejudicInfo>
    <GeneralInfo>
        <PlateformCode>CPI000408</PlateformCode>
        <UUID>GAP2018061313591451752</UUID>
        <Md5Value>e42f2184335f49c407c8abb24f05ab9f</Md5Value>
    </GeneralInfo>
    <Prejudication>
        <MktProdType>A202009-PRE</MktProdType>
        <cooprProdType>02</cooprProdType>
        <AppliName>李金城</AppliName>
        <AppliIdType>01</AppliIdType>
        <AppliIdNo>513723199303159470</AppliIdNo>
        <AppliSex>1</AppliSex>
        <AppliBirth>1993-03-15</AppliBirth>
        <AppliIdMobile>15528671315</AppliIdMobile>
    </Prejudication>
</PrejudicInfo>
xml;
        $req = new \GuzzleHttp\Client(['verify' => false]);
        $resp = $req->post($url, [
            'body' => $xml
        ]);
        var_dump($resp->getBody()->getContents());
        exit;
    }

    /**
     * fico pic-insure 影像资料传输接口
     */
    public function actionFicoPicInsure()
    {
        $url = "http://partnertest.mypicc.com.cn/ecooperation/SendImage/picInsure.do";
        $postData = [
            'plateformcode' => "CPI000408",
            'prejudicno' => "CSUDD20180000Q000E00626312420922",
            'MktProdType' => "APPLY",
            'filename' => "/www/wwwroot/yii2work/console/runtime/wodrow.win.cert.png",
        ];
        $req = new \GuzzleHttp\Client(['verify' => false]);
        $resp = $req->post($url, [
            'form_params' => $postData,
        ]);
        var_dump($resp->getBody()->getContents());
        exit;
    }

    /**
     * fico add-file 新增影像附件通知接口
     */
    public function actionFicoAddFile()
    {
        $url = "http://partnertest.mypicc.com.cn/ecooperation/Uinsured/addFile.do";
        $xml = <<<xml
<?xml version='1.0' encoding='GBK'?>
<PACKET type='REQUEST' version='1.0'>
    <requesthead>
        <request_type></request_type>
        <uuid>8be814c1-a841-4350-9dad-1a990bb5d11b</uuid>
        <sender></sender>
        <server_version>1</server_version>
        <user></user>
        <password></password>
        <flowintime>2013-06-03 09:58:50.846</flowintime>
    </requesthead>
    <AddImageInfo>
        <ProposalNo></ProposalNo>
        <AddTimes></AddTimes>
    </AddImageInfo>
</PACKET>
xml;
        $req = new \GuzzleHttp\Client(['verify' => false]);
        $resp = $req->post($url, [
            'body' => $xml
        ]);
        var_dump($resp->getBody()->getContents());
        exit;
    }

    /**
     * che300 品牌列表
     */
    public function actionChe300CarBrandList()
    {
        $url = "http://testapi.che300.com/service/getCarBrandList";
        $post_data = [
            'token' => "49e9277139cc259bbecf43e9f4f75981",
        ];
        $client = new Client();
        $resp = $client->get($url, $post_data)->send();
        return json_decode($resp->content);
    }

    /**
     * che300 车系列表
     * @param string $brandId 品牌id
     */
    public function actionChe300CarSeriesList($brandId = 6)
    {
        $url = "http://testapi.che300.com/service/getCarSeriesList";
        $post_data = [
            'token' => \common\components\che300\Config::$token,
            'brandId' => $brandId, // 品牌标识，可以通过车300品牌数据接口拿回所有的品牌信息，从而提取品牌标识。
        ];
        $client = new Client();
        $resp = $client->get($url, $post_data)->send();
        return json_decode($resp->content);
    }

    /**
     * che300 车型列表
     */
    public function actionChe300CarModelList()
    {
        $url = "http://testapi.che300.com/service/getCarModelList";
        $post_data = [
            'token' => "49e9277139cc259bbecf43e9f4f75981",
            'seriesId' => 76, // 车系标识，可以通过车300车系数据接口拿回车系信息，从而提前车系标识。
        ];
        $client = new Client();
        $resp = $client->get($url, $post_data)->send();
        return json_decode($resp->content);
    }

    /**
     * che300 城市列表
     */
    public function actionChe300CityAll()
    {
        $url = "http://testapi.che300.com/service/getAllCity";
        $post_data = [
            'token' => "49e9277139cc259bbecf43e9f4f75981",
        ];
        $client = new Client();
        $resp = $client->get($url, $post_data)->send();
        return json_decode($resp->content);
    }

    /**
     * che300 车型库的版本号
     */
    public function actionChe300CurrentVersion()
    {
        $url = "http://testapi.che300.com/service/common/eval";
        $post_data = [
            'token' => "49e9277139cc259bbecf43e9f4f75981",
            'oper' => "exportModel",
        ];
        $client = new Client();
        $resp = $client->get($url, $post_data)->send();
        return json_decode($resp->content);
    }

    /**
     * che300 精准估值
     */
    public function actionChe300UserdCarPrice()
    {
        $url = "http://testapi.che300.com/service/getUsedCarPrice";
        $post_data = [
            'token' => "49e9277139cc259bbecf43e9f4f75981",
            'modelId' => "25201", // 车型标识，可以通过车300车型列表数据接口拿回车300所支持的所有车型相关信息，也可以申请合作成功之后提供网站自己的车型信息进行两者之间的映射。
            'regDate' => "2015-11", // 待估车辆的上牌时间（格式：yyyy-MM）。
            'mile' => "4", // 待估车辆的公里数，单位万公里。
            'zone' => "154", // 城市标识，可以通过车300城市列表数据接口拿回车300所支持的所有城市相关信息，也可以申请合作成功之后提供网站自己的城市信息进行两者之间的映射。
        ];
        $client = new Client();
        $resp = $client->get($url, $post_data)->send();
        return json_decode($resp->content);
    }
}